﻿using Bootstrap.Definition.Events;
using Bootstrap.Helper;
using Bootstrap.Template.DropDown;
using Bootstrap.Template.TemplateInnerItem;
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Bootstrap.Control
{

    [ToolboxData("<{0}:BootstrapDropDown runat=server></{0}:BootstrapDropDown>")]
    public class BootstrapDropDown : WebControl, IPostBackDataHandler
    {
        #region Properties

        public bool PostBack { get; set; }

        public int SelectedIndex { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public List<AbstractBootstrapItem> InnerList { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public string DefaulText { get; set; }

        #endregion

        #region Events

        public event EventHandler SelectedIndexChanged;

        #endregion

        #region Methods

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.Page.RegisterRequiresPostBack(this);
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            writer.Write(GetHtml(this.InnerList));
        }

        public string GetHtml(List<AbstractBootstrapItem> innerList)
        {
            string result = string.Empty;

            BootstrapDropDownTemplateItem beginTemplateItem = new BootstrapDropDownTemplateItem();

            beginTemplateItem.ClientID = ValueHelper.GetDefaultValue<string>(this.UniqueID, string.Empty);
            beginTemplateItem.DefaultText = ValueHelper.GetDefaultValue<string>(this.DefaulText, "Lütfen Seçiniz");

            BootstrapDropDownTemplateBegin beginTemplate = new BootstrapDropDownTemplateBegin(beginTemplateItem);


            result += beginTemplate.TransformText();

            foreach (var item in innerList)
            {
                result += ((IInnerItem)item).GetTemplate();
            }

            BootstrapDropDownTemplateEnd endTempalte = new BootstrapDropDownTemplateEnd();

            result += endTempalte.TransformText();

            return result;
        }

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            return false;
        }

        public void RaisePostDataChangedEvent()
        {
            if (SelectedIndexChanged != null)
                SelectedIndexChanged(this, new SelectedIndexChangedEventArgs() { Index = SelectedIndex });
        }

        #endregion
    }
}
